<?php

namespace App\Console\Commands\Corn;

use App\Models\OwnerItem;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CreateOwnerItem extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'corn:create-owner-item';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建流水单据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $owners = \App\Models\Owner::query()->where('closed', true)->get();
        foreach ($owners as $owner) {
            if ($owner->cycle_unit == \App\Models\Owner::CYCLE_UNIT_YEAR) {
                $month = 12 * intval($owner->cycle) * intval($owner->now_cycle);
            } else if ($owner->cycle_unit == \App\Models\Owner::CYCLE_UNIT_MONTH) {
                $month = 1 * intval($owner->cycle) * intval($owner->now_cycle);
            }
            if ($owner->started_at->addMonth($month) < Carbon::now()) {;
                // 获取没有支付的订单， 然后发送短信通知租客缴纳费用
                if ($ownerItem = OwnerItem::query()->where('owner_id', $owner->id)
                    ->where('count', $owner->now_cycle)->doesntExist()) {
                    // 创建订单模板
                    $owner->items()->create([
                        'count' => $owner->now_cycle,
                        'status' => OwnerItem::STATUS_PAY_PENDING,
                        'started_at' => $owner->started_at->addMonth($month),
                        'ended_at' => $owner->started_at->addMonth($month + 1),
                        'rent' => $owner->cycle_price
                    ]);
                    $owner->now_cycle = $owner->now_cycle + 1;
                    $owner->save();
                }
            }
        }
    }
}
